package com.authine.cloudpivot.ext.kingdee;

import com.alibaba.cola.dto.RequestContext;
import com.authine.cloudpivot.ext.dto.kingDee.Certificate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @Author: liwei
 * @DateTime: 2021/7/2
 * @Description: TODO
 */
@Slf4j
public class KingDeeExecutor {


    // 本地服务器地址
//    public static String K3CloudUrl = "http://140.206.185.202:777/K3Cloud/";
    // 云服务器地址

    //http://10.8.0.167/k3cloud/  内网
    //http://47.96.75.88/k3cloud/
    //public String K3CloudUrl = "http://47.96.75.88/k3cloud/";

    private static Map<String, String> Func = new HashMap<String, String>() {{

        put("Login", "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc");
        put("Save", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
        put("View", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
        put("Submit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
        put("Audit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
        put("UnAudit", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
        put("StatusConvert", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        put("Delete", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Delete.common.kdsvc");
        put("BatchSave", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.BatchSave.common.kdsvc");
    }};

    private static String Cookie = "";

    private ObjectMapper objectMapper = new ObjectMapper();
    private RestTemplate restTemplate = new RestTemplate();


    /**
     * @param deal    地址
     * @param formId  表单Id
     * @param content Json内容
     * @return
     * @throws JsonProcessingException
     */
    private String invoke(String deal, String formId, String content,String urlPart) {

        log.info("调用金蝶接口 {} start ======================== requestUserId:{}", deal,RequestContext.getCorpLoginId());

        String url = urlPart + Func.get(deal);

        List<Object> parameters = new ArrayList<>();

        parameters.add(formId);
        parameters.add(content);
        try {
            Map<String, Object> params = new HashMap<>();

            params.put("format", 1);
            params.put("useragent", "ApiClient");
            params.put("rid", UUID.randomUUID().hashCode());
            params.put("parameters", chinaToUnicode(objectMapper.writeValueAsString(parameters)));
            params.put("timestamp", new Date().toString());
            params.put("v", "1.0");

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cookie", Cookie);
            headers.add("Content-Type", "application/json");

            /*connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);*/

            HttpEntity httpEntity = new HttpEntity<>(params, headers);


            //restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("utf-8")));

            ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {


                //TODO:

                return response.getBody();
            }
        } catch (JsonProcessingException j) {
            j.getMessage();
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }

    /**
     * Login
     *
     * @param dbId 账套
     * @param user 用户名
     * @param pwd  密码
     * @param lang 语言
     * @return
     * @throws Exception
     */
    public boolean login(String dbId, String user, String pwd, int lang,String urlPart) {

        log.info("调用金蝶接口 login start ======================== requestUserId:{}", RequestContext.getCorpLoginId());

        String url = urlPart + Func.get("Login");

        List<Object> parameters = new ArrayList<>();

        parameters.add(dbId);
        parameters.add(user);
        parameters.add(pwd);
        parameters.add(lang);
        try {
            Map<String, Object> params = new HashMap<>();

            params.put("format", 1);
            params.put("useragent", "ApiClient");
            params.put("rid", UUID.randomUUID().hashCode());
            params.put("parameters", chinaToUnicode(objectMapper.writeValueAsString(parameters)));
            params.put("timestamp", new Date().toString());
            params.put("v", "1.0");

            HttpHeaders headers = new HttpHeaders();
            headers.add("Cookie", Cookie);
            headers.add("Content-Type", "application/json;charset=utf-8");

            HttpEntity httpEntity = new HttpEntity<>(params, headers);


            ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getHeaders() != null) {

                String result = response.getBody();

                if (result != null && result.contains("\"LoginResultType\":1")) {

                    List<String> cookies = response.getHeaders().get("Set-Cookie");

                    if (cookies != null && !cookies.isEmpty()) {

                        for (String cookie : cookies) {
                            if (cookie.startsWith("kdservice-sessionid")) {
                                Cookie = cookie;
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return false;
    }

    // Save
    public String save(String formId, String content,String urlPart) {

        return invoke("Save", formId, content,urlPart);
    }

    // BatchSave
    public String batchSave(String formId, String content,String urlPart) {

        return invoke("BatchSave", formId, content,urlPart);
    }

    // View
    public String view(String formId, String content,String urlPart) {

        return invoke("View", formId, content,urlPart);
    }

    // Submit
    public String submit(String formId, String content,String urlPart) {

        return invoke("Submit", formId, content,urlPart);
    }

    // Audit
    public String audit(String formId, String content,String urlPart) {

        return invoke("Audit", formId, content,urlPart);
    }

    // UnAudit
    public String unAudit(String formId, String content,String urlPart) {

        return invoke("UnAudit", formId, content,urlPart);
    }

    // Status Convert
    public String statusConvert(String formId, String content,String urlPart) {

        return invoke("StatusConvert", formId, content,urlPart);
    }

    //Delete
    public String delete(String formId, String content,String urlPart) {

        return invoke("Delete", formId, content,urlPart);
    }


    /**
     * 把中文转成Unicode码
     *
     * @param str
     * @return
     */
    private static String chinaToUnicode(String str) {
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            // 汉字范围 \u4e00-\u9fa5 (中文)
            if (chr1 >= 19968 && chr1 <= 171941) {
                result += "\\u" + Integer.toHexString(chr1);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }


    public static String content = "{\"Result\":{\"ResponseStatus\":{\"ErrorCode\":500,\"IsSuccess\":false,\"Errors\":[{\"FieldName\":\"FName\",\"Message\":\"该员工编号已经存在\",\"DIndex\":0,\"FNumber\":\"344534\"}],\"SuccessEntitys\":[],\"SuccessMessages\":[],\"MsgCode\":0},\"NeedReturnData\":[]}} ";

    public static void main(String[] args) {


    }

    public String saveLogic(String dbId, String user, String pwd, int lang,String urlPart,Certificate certificate) {

        //先调用登录接口，后调保存数据接口
        // todo 注意目前项目模块没有配置文件，先将数据固定写实，待优化
        log.info("调用金蝶接口 start ======================== requestUserId:{}", RequestContext.getCorpLoginId());

        if (login(dbId, user, pwd, lang,urlPart)) {
            String invoke = batchSave(certificate.getFormEnum().toString(), certificate.getContent(),urlPart);
            log.info("保存逻辑返回结果 result:{}",invoke);
            return invoke;
        }
        return null;
    }


    public String deleteLogic(String dbId, String user, String pwd, int lang,String urlPart,Certificate certificate) {

        //先调用登录接口，后调删除数据接口
        // todo 注意目前项目模块没有配置文件，先将数据固定写实，待优化

        if (login(dbId, user, pwd, lang,urlPart)) {
            String invoke = delete(certificate.getFormEnum().toString(), certificate.getContent(),urlPart);
            log.info("删除逻辑返回结果 result:{}",invoke);
            return invoke;
        }
        return null;
    }



}
